package cn.zbmao.web.Timer;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;


public class TimerManager {
	
	private static final long PERIOD_DAY = 24*60*60*1000;
	private static Timer timer = new Timer(false);

    /**
     * 定时任务的配置
     */
	public TimerManager(){
		System.out.println("-------------------------------------------定时任务初始化");
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 10);
		calendar.set(Calendar.MINUTE, 41);
		calendar.set(Calendar.SECOND, 0);
		Date date=calendar.getTime();

        Calendar calendarSuccessful = Calendar.getInstance();
        calendarSuccessful.set(Calendar.DAY_OF_WEEK,6);
        calendarSuccessful.set(Calendar.HOUR_OF_DAY,1);
        calendarSuccessful.set(Calendar.MINUTE,3);
        calendarSuccessful.set(Calendar.SECOND,0);
        Date dateSuccessful=calendarSuccessful.getTime();

		 //如果第一次执行定时任务的时间 小于 当前的时间
		 //此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。
		if(date.before(new Date())){
			date=this.addDay(date, 1);
		}

        if(dateSuccessful.before(new Date())){
            dateSuccessful = this.addDay(dateSuccessful,7);
        }



		CrmDataTimerTasker taskMail = new CrmDataTimerTasker();//这个是你的任务
		SuccessfulDateTimerTasker taskerSuccessful = new SuccessfulDateTimerTasker();


		timer.schedule(taskMail, date,PERIOD_DAY);
        timer.schedule(taskerSuccessful,dateSuccessful,PERIOD_DAY);
		
		
	}
	
	public static void cancel(){
		timer.cancel();
	}

    /**
     *
     * @param date 日期
     * @param num 添加的时间
     * @return
     * 在date时间上添加num天
     */
	public Date addDay(Date date,int num){
		
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, num);
		return calendar.getTime();
		
	}
	
	
	
}
